package com.ta.market;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.ta.util.ImageUtil;
import com.ta.util.Logu;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissonItem;

public class SplashActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
    private String videoUrl = "http://cdn.mdownl.cn:8080/resource/video/admin20180604173000.mp4";
    public static final String sep = File.separator;
    public static final String SD = Environment.getExternalStorageDirectory().getAbsolutePath();
    public static final String VIDEOPATH = SD + sep + ".coopenVideo" + sep + "file" + sep + "down" + sep + "video" + sep + "admin20180604173000.mp4";

    private SurfaceHolder mSurfaceHolder;
    private MediaPlayer mMediaPlayer;
    private int mCurrentPlayPosition = 0;
    private boolean isFirst = true;

    @Bind(R.id.splash_surface_view)
    SurfaceView mSurface;
    @Bind(R.id.splash_btn_ad)
    Button mBtnAD;
    @Bind(R.id.splash_btn_time)
    Button mBtnTime;
    @Bind(R.id.splash_image_view)
    ImageView mIconView;

    private File mFile;
    private AudioManager mAudioManager;
    private int mTotalTime = 0;
    private Timer mTimerTask;
    private Handler handler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logu.i("onCreate");
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        initHandler();
        checkPermission();
        initDataSource();
    }

    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                mTotalTime -= 1;
                if (mTotalTime < 0) {
                    mBtnTime.setText("跳过");
                    cancelTimeTask();
                } else {
                    mBtnTime.setText("剩余" + mTotalTime + "秒");
                }
            }
        };
    }

    private void initDataSource() {
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mFile = new File(VIDEOPATH);
        if (mFile.exists() && mFile.isFile()) {
            initViews();
        } else {

            Logu.i("进入后台下载视频");
        }
    }

    private void checkPermission() {
        List<PermissonItem> permissonItems = new ArrayList<>();
        PermissonItem permissonItem = new PermissonItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "外部存储", R.drawable.permission_ic_memory);
        permissonItems.add(permissonItem);
        HiPermission.create(this)
                .permissions(permissonItems)
                .checkMutiPermission(new PermissionCallback() {
                    @Override
                    public void onClose() {
                        Logu.i("用户关闭了权限申请");
                    }

                    @Override
                    public void onFinish() {
                        Logu.i("所有权限申请完毕");
                    }

                    @Override
                    public void onDeny(String permisson, int position) {
                        Logu.i("onDeny");
                    }

                    @Override
                    public void onGuarantee(String permisson, int position) {
                        Logu.i("onGuarantee");
                    }
                });
    }

    private void initViews() {
        mSurfaceHolder = mSurface.getHolder();
        if (Build.VERSION.SDK_INT <= 14) {
            mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        mSurfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            initMediaPlayer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initMediaPlayer() throws IOException {
        Logu.i("initMediaPlayer");
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDisplay(mSurfaceHolder);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setDataSource(mFile.getAbsolutePath());
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnSeekCompleteListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnErrorListener(this);
            mMediaPlayer.prepareAsync();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mCurrentPlayPosition = mMediaPlayer.getCurrentPosition();
            }
            releaseMediaPlayer();
        }
        cancelTimeTask();
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        Logu.i("isFirst = " + isFirst);
        if (isFirst) {
            mTotalTime = mp.getDuration() / 1000;
        }
        isFirst = false;
        if (mBtnAD != null && mBtnAD.getVisibility() == View.INVISIBLE) {
            mBtnAD.setVisibility(View.VISIBLE);
        }
        if (mBtnTime != null && mBtnTime.getVisibility() == View.INVISIBLE) {
            mBtnTime.setVisibility(View.VISIBLE);
            mBtnTime.setText("剩余" + mTotalTime + "秒");
        }
        if (mIconView != null && mIconView.getVisibility() == View.INVISIBLE) {
            mIconView.setVisibility(View.VISIBLE);
            Bitmap bitmap = ImageUtil.toRoundCornerImage(BitmapFactory.decodeResource(getResources(), R.drawable.haimai), 100);
            mIconView.setImageBitmap(bitmap);
        }
        mp.seekTo(mCurrentPlayPosition);
    }

    @Override
    public void onSeekComplete(MediaPlayer mp) {
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
        mp.start();
        startTimeTask();
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        Logu.i("onError -- what = " + what + " -- extra = " + extra);
        if (mFile.exists()) {
            mFile.delete();
        }
        startActivity();
        return true;
    }

    private void startActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    private void startTimeTask() {
        if (mTimerTask == null) {
            mTimerTask = new Timer();
            mTimerTask.schedule(new TimerTask() {
                @Override
                public void run() {
                    handler.obtainMessage().sendToTarget();
                }
            }, 1000, 1000);
        }
    }


    @OnClick(R.id.splash_btn_time)
    public void onViewClicked(View view) {
        if (mBtnTime.getText().equals("跳过")) {
            startActivity();
        }
    }

    @Override
    protected void onDestroy() {
        cancelTimeTask();
        releaseMediaPlayer();
        releaseHandler();
        releaseView();
        super.onDestroy();
    }

    private void releaseView() {
        if (mBtnAD != null) {
            mBtnAD = null;
        }
        if (mBtnTime != null) {
            mBtnTime = null;
        }
        if (mSurface != null) {
            mSurface = null;
        }
        setContentView(R.layout.activity_null);
    }

    private void releaseHandler() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    private void cancelTimeTask() {
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }

    private void releaseMediaPlayer() {
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }


}
